/**
 * Created by huachuan on 2016/1/7.
 */
angular.module('shopdetailcontrollers',[])
  //店铺详情的Controller
  .controller('ShopDetailCtrl',function($scope,$rootScope,$state,$stateParams,$cordovaStatusbar,$ionicActionSheet,$cordovaFileTransfer,Shop,Loading,ENV,History,Toast){
        var shopId = $stateParams['shopId'];
        $scope.picPath = ENV.picPath;
        //获取店铺详情
        Loading.showLoading();
        Shop.getShopDetail(shopId);
        $scope.$on('Shop.shopDetailUpdated',function(){
          $scope.shop = Shop.getShopDetailJson();
          var shopAddr = $scope.shop.shop_detail_addr;
          if(shopAddr.length>21){
            $scope.shop.shop_detail_addr = shopAddr.substring(0,21)+"<br/>"+shopAddr.substring(21);
          }
          Loading.hideLoading();
          console.log($scope.shop);
        });
        //对商铺大图进行处理
    //酒窝显示大图
    $scope.showBigImage= function(){
      var items = [{
        src:$scope.picPath+"big_"+$scope.shop.shop_img_url,
        w:$scope.shop.w,
        h:$scope.shop.h
      }];
      var pswpElement = document.querySelectorAll('.pswp')[0];
      var options = {
        index: 1,
        history: false,
        focus: false,
        loop: false,
       /*  pinchToClose:false,
         closeOnVerticalDrag:false,*/
        showAnimationDuration: 100,
        hideAnimationDuration: 100,
        backButtonHideEnabled:true,
        captionAndToolbarFlipPosition:true,
        loadingIndicatorDelay:100
      };
      $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
      $rootScope.gallery.init();
      //$cordovaStatusbar.hide();
    }
    //长按下载
    $rootScope.downloadHomeImg = function(){
      var url = $rootScope.gallery.currItem.src;
      var timestamp=new Date().getTime();
      var targetPath = targetPath = cordova.file.externalRootDirectory+"winelife/winelife_shop_"+timestamp+".jpg";
      var trustHosts = true;
      var options = {};
      $ionicActionSheet.show({
        buttons: [
          {text: '保存到手机相册'}
        ],
        cancelText: '取消',
        buttonClicked: function (index) {
          if(index==0){
            $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
              .then(function(result) {
                Toast.showMessage("保存成功");
              }, function(err) {
                Toast.showMessage("保存成功");
              }, function (progress) {
              });
          }
          return true;
        }
      });
    }
    //单击缩小图片
    $rootScope.smallPicture = function(){
      $rootScope.gallery.close();
      // $cordovaStatusbar.show();
    }

      /************跳转到官方微博或者点击保存微信二维码************/
        //长按保存图片
      $scope.downloadImg = function(){
        var timestamp=new Date().getTime();
        var url = ENV.picPath+$scope.shop.shop_weixin_code_url;
        var targetPath = cordova.file.externalRootDirectory +"winelife/winelife_shop"+timestamp+".jpg";
        var trustHosts = true;
        var options = {};
        $ionicActionSheet.show({
          buttons: [
            {text: '保存到手机相册'}
          ],
          cancelText: '取消',
          buttonClicked: function (index) {
            if(index==0){
              $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
                .then(function(result) {
                  Toast.showMessage("保存成功");
                }, function(err) {
                  Toast.showMessage("保存成功");
                }, function (progress) {
                });
            }
            return true;
          }
        });
      }

    $scope.phoneCall = function (phoneNum) {
      if(phoneNum!=undefined&&phoneNum!=''){
        if(ionic.Platform.isAndroid()){
          document.location.href = "tel:"+phoneNum;
        }else if(ionic.Platform.isIOS()){
          phonedialer.dial(phoneNum,function(err) {
            if (err == "feature")
              if (err == "empty")
                Toast.showMessage("未知的电话号码");
          });
        }
      }else{
        Toast.showMessage("号码不存在");
      }
    }

    $scope.goShopWeibo = function () {
      var browser = cordova.ThemeableBrowser.open($scope.shop.shop_weibo, '_system', {
        statusbar: {
          color: '#ffffffff'
        },
        toolbar: {
          height: 44,
          color: '#970b34'
        },
        title: {
          color: '#ffffff',
          staticText: '官方微博',
          showPageTitle: true
        },
        backButton: {
          wwwImage: 'img/back-btn.png',
          wwwImagePressed: 'img/back-btn.png',
          wwwImageDensity: 2,
          align: 'left',
          event: 'backPressed'
        },
        backButtonCanClose: true
      });

      browser.addEventListener('backPressed', function (e) {
        browser.close();
      });
    }



    $scope.guide = function(){
      var guideInfo = {
        shop_baidu_addr:$scope.shop.shop_baidu_addr,
        shop_detail_addr:$scope.shop.shop_detail_addr
      };
      Shop.setGuideInfo(guideInfo);
      $state.transitionTo("shop-guide");
    };

    //返回
    $scope.goback = function(){
      History.goback();
    }
  })
  //店铺导航
.controller('ShopGuideCtrl',function($scope,$state,History,Shop,LBS){

    var  guideInfo = '';
    var map;
    $scope.$on('$ionicView.beforeEnter',function(){
      guideInfo  = Shop.getGuideInfo();
      LBS.getPosition();
    });

    // 百度地图API功能
    $scope.$on('LBS.locationSuccess',function(){
      var location = LBS.getLocation();
      map = new BMap.Map("allmap");
      var myPoint = new BMap.Point(location.longitude,location.latitude);
      map.centerAndZoom(myPoint,11);
      map.addControl(new BMap.NavigationControl());
      map.addControl(new BMap.GeolocationControl());
      map.addControl(new BMap.MapTypeControl());
      map.addControl(new BMap.ScaleControl());
      map.addControl(new BMap.OverviewMapControl());
      var convertor = new BMap.Convertor();
      var pointArr = [];
      pointArr.push(myPoint);
      convertor.translate(pointArr, 1, 5, translateCallback);
    });

    translateCallback = function(data) {
      if (data.status === 0) {
        //获取到店铺的定位坐标
        var array = guideInfo.shop_baidu_addr.split(",");
        //店铺坐标
        var shopPoint = new BMap.Point(array[0],array[1]);
        var translatePoint = data.points[0];
        //路线导航
        var driving = new BMap.DrivingRoute(map, {renderOptions:{map: map, autoViewport: true}});
        driving.search(translatePoint, shopPoint);
        //获取到当前定位坐标的地理位置
      }
    }
    //返回
    $scope.goback = function(){
      History.goback();
    }
  });
